<template>
  <div class="">
    <div class="container">
      <div class="sidebar">
        <ul>
          <li
            v-for="(item, index) in menuItems"
            :key="index"
            @click="selectPage(index)"
            :class="{ active: selectedPageIndex == index }"
          >
            {{ item.title }}
          </li>
        </ul>
      </div>
      <div class="content" ref="content" @scroll="handleScroll">
        <div
          v-for="(item, index) in menuItems"
          :key="index"
          :id="item.anchor"
          class="name"
        >
          {{ item.title }}内容
          <!-- 内容区域 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/*
  1.主要思路就是: 处于右侧盒子中顶部一小块的就被选中
*/
export default {
  data() {
    return {
      selectedPageIndex: 0,
      menuItems: [
        { title: "目录项1", anchor: "section1" },
        { title: "目录项2", anchor: "section2" },
        { title: "目录项3", anchor: "section3" },
        { title: "目录项4", anchor: "section4" },
        { title: "目录项5", anchor: "section5" },
        { title: "目录项6", anchor: "section6" },
        { title: "目录项7", anchor: "section7" },
        { title: "目录项8", anchor: "section8" },
      ],
      timeOut: null,
    };
  },
  methods: {
    selectPage(index) {
      this.selectedPageIndex = index;
      let dom = document.getElementById(this.menuItems[index].anchor);
      dom.scrollIntoView({
        behavior: "smooth",
      });
    },
    handleScroll() {
      // this.timeOut && clearInterval(this.timeOut);
      let par = this.$refs.content;
      this.timeOut = setTimeout(() => {
        let scrollTop = par.scrollTop;
        for (let i = 0; i < this.menuItems.length; i++) {
          var offsetTop = document.getElementById(
            this.menuItems[i].anchor
          ).offsetTop;
          var offsetHeight = document.getElementById(
            this.menuItems[i].anchor
          ).offsetHeight;
          if (
            scrollTop >= offsetTop - 20 &&
            scrollTop < offsetTop + offsetHeight - 20
          ) {
            this.selectedPageIndex = i;
          }
        }
      }, 300);
    },
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  position: relative;
}

.sidebar {
  width: 200px;
  background-color: #f0f0f0;
}

.sidebar ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sidebar li {
  padding: 10px;
  cursor: pointer;
}

.sidebar li.active {
  background-color: #ccc;
}

.content {
  flex: 1;
  overflow-y: auto;
  height: 400px;
}
.name {
  width: 100%;
  height: 100px;
  border: 1px solid red;
  box-sizing: border-box;
  margin-bottom: 10px;
}
.ddd {
  width: 100%;
  height: 800px;
}
</style>
